﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Interactivity;

namespace WirelessAccessPoint.Interactivity
{
    /// <summary>
    /// PasswordBoxがGotFocusする際に入力文字を全選択するビヘイビアです。
    /// 
    /// 【使用方法】
    /// <i:Interaction.Behaviors>
    ///     <behavior:SelectAllPasswordBoxBehavior IsEnable="True" />
    /// </i:Interaction.Behaviors>
    /// </summary>
    public class SelectAllPasswordBoxBehavior : Behavior<PasswordBox>
    {
        public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.Register(
            "IsEnabled",
            typeof(bool),
            typeof(SelectAllPasswordBoxBehavior),
            new FrameworkPropertyMetadata(true));

        public bool IsEnabled
        {
            get { return (bool) this.GetValue(IsEnabledProperty); }
            set { this.SetValue(IsEnabledProperty, value); }
        }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.GotFocus += this.GotFocus;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            this.AssociatedObject.GotFocus -= this.GotFocus;
        }

        private void GotFocus(object sender, RoutedEventArgs e)
        {
            if (this.IsEnabled)
            {
                (sender as PasswordBox).SelectAll();
            }
        }
    }
}
